package com.ma.chapter8.readwrite;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName DataContainer
 * @Author: mayongqiang
 * @DATE 2022/3/24 23:30
 * @Description: 读写锁演示
 */
@Slf4j(topic = "m.DataContainer")
public class TestReadWriteLock {
    public static void main(String[] args) {
        DataContainer container = new DataContainer();
        new Thread(()->{
            container.write();
        },"t1").start();

        sleep(0.8);

        new Thread(()->{

            container.write();
        },"t2").start();
    }
}

@Slf4j(topic = "m.DataContainer")
class DataContainer {
    private Object data;
    private ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock r = rw.readLock();
    private ReentrantReadWriteLock.WriteLock w = rw.writeLock();


    public Object read() {
        log.debug("获取读锁....");
        r.lock();
        try {
            log.debug("读取");
            sleep(1);
            return data;
        }finally {
            log.debug("释放读锁...");
            r.unlock();
        }

    }

    public void write() {
        w.lock();
        log.debug("加写锁...");
        try {
            log.debug("写入");
        } finally {
            log.debug("释放写锁...");
            w.unlock();
        }
    }
}
